package models

import (
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

func QueryEulerRepoOrigin(ogk *OpenEulerRepoOrigin, field ...string) error {
	o := orm.NewOrm()
	err := o.Read(ogk, field...)
	return err
}

func QueryEulerRepoOriginByNmae(packageName string) (oer []OpenEulerRepoOrigin) {
	o := orm.NewOrm()
	num, geErr := o.Raw("select *"+
		" from cve_open_euler_repo_origin where package_name = ?", packageName).QueryRows(&oer)
	if num == 0 {
		logs.Error("QueryEulerRepoOriginByNmae, Get data does not exist, geErr: ", geErr)
	}
	return
}

func FindEulerRepoOrigin(packageName, version string) (OpenEulerRepoOrigin, error) {
	o := orm.NewOrm()
	data := OpenEulerRepoOrigin{PackageName: packageName, Version: version}
	err := o.Read(&data, "PackageName", "Version")
	return data, err
}

// insert data
func InsertEulerRepoOrigin(ogk *OpenEulerRepoOrigin) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(ogk)
	return id, err
}

func UpdateEulerRepoOrigin(ogk *OpenEulerRepoOrigin, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(ogk, fields...)
	return err
}

// DeleteEulerRepoOrigin delete
func DeleteEulerRepoOrigin(id int64) error {
	o := orm.NewOrm()
	_, err := o.Raw("delete from cve_open_euler_repo_origin where id = ?", id).Exec()
	return err
}

func FindGitOpenEuler(packageName, version string) (GitOpenEuler, error) {
	o := orm.NewOrm()
	data := GitOpenEuler{PackageName: packageName, Version: version, Source: "openeuler"}
	err := o.Read(&data, "PackageName", "Version", "Source")
	return data, err
}

// DeleteGitOpenEuler delete data of ng
func DeleteGitOpenEuler(id int64) error {
	o := orm.NewOrm()
	_, err := o.Raw("delete from cve_git_open_euler where source != ? and git_id = ?", "ng", id).Exec()
	return err
}

func FindGitPackageInfo(packageName, version string) (GitPackageInfo, error) {
	o := orm.NewOrm()
	data := GitPackageInfo{PackageName: packageName, Version: version}
	err := o.Read(&data, "PackageName", "Version")
	return data, err
}

// DeleteGitPackageInfo delete
func DeleteGitPackageInfo(id int64) error {
	o := orm.NewOrm()
	_, err := o.Raw("delete from cve_git_package_info where detail_id = ?", id).Exec()
	return err
}

func GetEulerYamlList(yamlId int64, count int) (oer []OpenEulerRepoOrigin) {
	o := orm.NewOrm()
	num, geErr := o.Raw("select *"+
		" from cve_open_euler_repo_origin where id > ? order by id asc limit ?", yamlId, count).QueryRows(&oer)
	if num == 0 {
		logs.Error("GetEulerYamlList, Get data does not exist, geErr: ", geErr)
	}
	return
}

func GetGitOpenEulerList(gitId int64, count int) (goe []GitOpenEuler) {
	o := orm.NewOrm()
	num, geErr := o.Raw("select *"+
		" from cve_git_open_euler where git_id > ? and package_id < ? and status = 1 order by git_id asc limit ?",
		gitId, 10000000, count).QueryRows(&goe)
	if num == 0 {
		logs.Error("GetGitOpenEulerList, Get data does not exist, geErr: ", geErr)
	}
	return
}
